﻿using System.Reflection;
using Autofac;
using Management.Domain.IRepository;
using Management.EntityFrameworkCore.Repository;
using Module = Autofac.Module;

namespace Management.HttpApi.Host.Register
{
    public class AutoFacModuleRegister : Module
    {
        /// <summary>
        ///加载程序集
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            //获得需要注入的Services
            Assembly[] servicesAssembly = GetServiceAssembly();

            //注册IRepository
            builder.RegisterGeneric(typeof(EFRepository<>)).As(typeof(IRepository<>));

            //注册Service
            builder.RegisterAssemblyTypes(servicesAssembly)
                   .AsImplementedInterfaces()
                   .InstancePerLifetimeScope();
        }

        /// <summary>
        /// 获得需要注入的服务
        /// </summary>
        /// <returns></returns>
        private static Assembly[] GetServiceAssembly()
        {
            List<Assembly> assembly = new List<Assembly>();

            //获取当前路径
            string basePath = AppContext.BaseDirectory;

            //获得需要注入的Services
            Assembly lLoadAssembly = Assembly.LoadFrom(Path.Combine(basePath, "Management.Application.dll"));

            foreach (var lAssembly in lLoadAssembly.GetTypes())
            {
                if (lAssembly.Name.Contains("Service"))
                {
                    assembly.Add(lAssembly.Assembly);
                }
            }

            return assembly.ToArray();
        }
    }
}
